<template>
  <div v-if="showCard">


    <!--  模糊搜索框-->
    <a-form
      layout="inline"
      :model="formState"
      @finish="handleFinish"
      @finishFailed="handleFinishFailed"
      style="margin-bottom: 10px"
    >
      <div>
        <tr>
          <td>
            <a-form-item>
              <a-input v-model:value="formState.smlTem" placeholder="温度范围下界" style="width: 120px">
              </a-input>
            </a-form-item>
          </td>
          <td>
            <a-form-item>
              <a-input v-model:value="formState.bigTem" placeholder="温度范围上界" style="width: 120px">
              </a-input>
            </a-form-item>
          </td>
          <td>
            <a-form-item>
              <a-input v-model:value="formState.smlHum" placeholder="湿度范围下界" style="width: 120px">
              </a-input>
            </a-form-item>
          </td>
          <td>
            <a-form-item>
              <a-input v-model:value="formState.bigHum" placeholder="湿度范围上界" style="width: 120px">
              </a-input>
            </a-form-item>
          </td>
          <td>
            <a-form-item>
              <a-input v-model:value="formState.beep" placeholder="蜂鸣器状态" style="width: 120px">
              </a-input>
            </a-form-item>
          </td>
          <td>
            <a-form-item>
              <a-input v-model:value="formState.led" placeholder="LED状态" style="width: 120px">
              </a-input>
            </a-form-item>
          </td>
        </tr>
      </div>
      <div style="margin-top: 5px">
        <tr>
          <td>
            <a-form-item>
              <a-input v-model:value="formState.smlAdcx" placeholder="光照强度下界" style="width: 120px">
              </a-input>
            </a-form-item>
          </td>
          <td>
            <a-form-item>
              <a-input v-model:value="formState.bigAdcx" placeholder="光照强度上界" style="width: 120px">
              </a-input>
            </a-form-item>
          </td>
          <td>
            <a-space direction="vertical" :size="12">
              <a-range-picker
                :show-time="{ format: 'HH:mm:ss' }"
                format="YYYY-MM-DD HH:mm:ss"
                :placeholder="['Start Time', 'End Time']"
                @change="onRangeChange"
                @ok="onRangeOk"
              />
            </a-space>
          </td>
          <td></td>
          <td></td>
          <td>
            <a-form-item>
              <a-button
                type="primary"
                @click="search()"
              >
                查询
              </a-button>
              <a-button
                style="margin-left: 5px"
                @click="reSet"
              >
                重置
              </a-button>
            </a-form-item>
          </td>
        </tr>
      </div>
      <hr>
      <a-form-item>
        <a-button
          type="primary"
          @click="outFile()"
        >
          导出
        </a-button>
      </a-form-item>
    </a-form>
    <hr>

    <!--  数据显示部分-->
    <a-table :columns="columns" :data-source="dataSource.data" bordered>
      <template #bodyCell="{ column, text, record }">
        <template
          v-if="['device_code', 'beep_state', 'led_state','tem','hum','adcx','creat_time'].includes(column.dataIndex)">
          <div>
            <a-input
              v-if="editableData[record.key]"
              v-model:value="editableData[record.key][column.dataIndex]"
              style="margin: -5px 0"
            />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <div class="editable-row-operations">
          <span v-if="editableData[record.key]">
            <a-typography-link @click="save(record.key)">Save</a-typography-link>
            <a-popconfirm title="Sure to cancel?" @confirm="cancel(record.key)">
              <a>Cancel</a>
            </a-popconfirm>
          </span>
            <span v-else>
            <a @click="edit(record.key)">Edit</a>
              <a-button type="primary" @click="myDelete(record.key)">Delete</a-button>
              <!--            <a @click="myDelete(record.key)">Delete</a>-->
          </span>
          </div>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script setup>
  import { cloneDeep } from 'lodash-es'
  import { reactive, ref, onBeforeMount, onMounted, createVNode, onUnmounted } from 'vue'
  import { getDataByDeviceCode, getDataByDeviceCodePage, deleteById,download } from '../../api/dataManage'
  import { Modal, message } from 'ant-design-vue'
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue'

  const formState = reactive({
    bigTem: '',
    smlTem: '',
    bigHum: '',
    smlHum: '',
    bigAdcx: '',
    smlAdcx: '',
    beep: '',
    led: '',
    bigCreateTime: '',
    smlCreateTime: ''
  })
  const handleFinish = values => {
    console.log(values, formState)
  }
  const handleFinishFailed = errors => {
    console.log(errors)
  }

  const search = async () => {
    dataSource.data = []

    let tempBeep = formState.beep
    let tempLed = formState.led
    if (formState.beep === '开' || formState.beep === '启' || formState.beep === '开启') {
      formState.beep = 1
    }
    if (formState.beep === '关' || formState.beep === '闭' || formState.beep === '关闭') {
      formState.beep = 0
    }

    if (formState.led === '开' || formState.led === '启' || formState.led === '开启') {
      formState.led = 1
    }
    if (formState.led === '关' || formState.led === '闭' || formState.led === '关闭') {
      formState.led = 0
    }

    // showCard.value=false
    let res = await getDataByDeviceCodePage(deviceCode, formState.bigTem, formState.smlTem, formState.bigHum, formState.smlHum, formState.bigAdcx,
      formState.smlAdcx, formState.beep, formState.led, formState.bigCreateTime, formState.smlCreateTime)
    let temp = res.data.data
    console.log('res', temp)
    // console.log('tempData', temp)
    temp.forEach(item => {
      let split = item.creatTime.split('T')
      dataSource.data.push({
        key: item.id.toString(),
        deviceCode: item.deviceCode,
        beepState: item.beepState === 0 ? '关闭' : '开启',
        ledState: item.ledState === 0 ? '关闭' : '开启',
        tem: item.tem,
        hum: item.hum,
        adcx: item.adcx,
        creatTime: split[0] + '  ' + split[1],
      })
    })
    // showCard.value=true
    formState.beep = tempBeep
    formState.led = tempLed
  }

  const reSet = () => {
    formState.bigTem = ''
    formState.smlTem = ''
    formState.bigHum = ''
    formState.smlHum = ''
    formState.beep = ''
    formState.led = ''
    formState.bigAdcx = ''
    formState.smlAdcx = ''
    formState.smlCreateTime = ''
    formState.bigCreateTime = ''
    showCard.value = false
    getData()
  }

  //*********日期选择
  // const startTime = ref('')
  // const endTime = ref('')
  const onChange = (value, dateString) => {
    console.log('Selected Time: ', value)
    console.log('Formatted Selected Time: ', dateString)
  }
  const onOk = value => {
    console.log('onOk: ', value)
  }
  const onRangeChange = (value, dateString) => {
    console.log('Selected Time: ', value)
    console.log('Formatted Selected Time: ', dateString)
    formState.smlCreateTime = dateString[0]
    formState.bigCreateTime = dateString[1]
  }
  const onRangeOk = value => {
    console.log('onOk: ', value)
  }

  const outFile = () => {
    alert("导出")
    // let tempBeep = formState.beep
    // let tempLed = formState.led
    // if (formState.beep === '开' || formState.beep === '启' || formState.beep === '开启') {
    //   formState.beep = 1
    // }
    // if (formState.beep === '关' || formState.beep === '闭' || formState.beep === '关闭') {
    //   formState.beep = 0
    // }
    //
    // if (formState.led === '开' || formState.led === '启' || formState.led === '开启') {
    //   formState.led = 1
    // }
    // if (formState.led === '关' || formState.led === '闭' || formState.led === '关闭') {
    //   formState.led = 0
    // }
    //
    // // showCard.value=false
    // let res = download(deviceCode, formState.bigTem, formState.smlTem, formState.bigHum, formState.smlHum, formState.bigAdcx,
    //   formState.smlAdcx, formState.beep, formState.led, formState.bigCreateTime, formState.smlCreateTime)
    //
    // console.log('res', res)
    // formState.beep = tempBeep
    // formState.led = tempLed
  }

  //****************************上面为搜索表单***********************************************************************

  //****************************下面为数据显示***********************************************************************

  const columns = [
    {
      title: '设备名称',
      dataIndex: 'deviceCode',
      width: '15%',
    },
    {
      title: '蜂鸣器状态',
      dataIndex: 'beepState',
      width: '10%',
    },
    {
      title: 'LED状态',
      dataIndex: 'ledState',
      width: '10%',
    },
    {
      title: '温度',
      dataIndex: 'tem',
      width: '10%',
    },
    {
      title: '湿度',
      dataIndex: 'hum',
      width: '10%',
    },
    {
      title: '光照强度',
      dataIndex: 'adcx',
      width: '10%',
    },
    {
      title: '采集时间',
      dataIndex: 'creatTime',
      width: '20%',
    },
    {
      title: 'operation',
      dataIndex: 'operation',
    }]

  const dataSource = reactive({
    data: []
  })
  const editableData = reactive({})
  //TODO 后期可以更改为动态设置
  const deviceCode = 'ID20221111'
  const edit = key => {
    editableData[key] = cloneDeep(dataSource.data.filter(item => key === item.key)[0])
  }

  const myDelete = (key) => {
    Modal.confirm({
      title: '您确定要删除这条数据吗？',
      icon: createVNode(ExclamationCircleOutlined),
      content: createVNode('div', {
        style: 'color:red;',
      }, '点击确认OK则将永久删除这条数据！'),
      async onOk () {
        // console.log('OK', key)
        deleteById(key)
        await sleep(200)
        getData()
        message.success('删除成功!')
      },
      onCancel () {
        // console.log('Cancel')
        message.success('取消成功!')
      },
      class: 'test',
    })
  }

  const sleep = (ms) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve()
      }, ms)
    })
  }

  const save = key => {
    Object.assign(dataSource.data.filter(item => key === item.key)[0], editableData[key])
    console.log(editableData[key])
    delete editableData[key]
  }
  const cancel = key => {
    delete editableData[key]
  }

  const showCard = ref(false)

  const getData = () => {
    showCard.value = false
    dataSource.data = []
    let res = getDataByDeviceCode(deviceCode)
    res.then(res => {
      // console.log('resData', res.data.data)
      let temp = res.data.data
      // console.log('tempData', temp)
      temp.forEach(item => {
        let split = item.creatTime.split('T')
        dataSource.data.push({
          key: item.id.toString(),
          deviceCode: item.deviceCode,
          beepState: item.beepState === 0 ? '关闭' : '开启',
          ledState: item.ledState === 0 ? '关闭' : '开启',
          tem: item.tem,
          hum: item.hum,
          adcx: item.adcx,
          creatTime: split[0] + '  ' + split[1],
        })
      })
      showCard.value = true
      // console.log('tableData', data)
    })
  }

  //*****************生命周期**********************************************************************
  onMounted(() => {
    getData()
  })


</script>
<style scoped>
  .editable-row-operations a {
    margin-right: 8px;
  }
</style>
